<?php

require_once 'classes/LightPressPlugin.php';

class CommentsList extends LightPressPlugin {
    
    var $constructor_args = array(
        'date_format'=>'custom date format',
        'limit'=>'number of posts to show');
    var $default_context = LP_CONTEXT_ALL;
    var $description = 'Display the top n most recent comments';
    
    var $active = true;
    var $hooks = array('sidebar');
    
    var $date_format;
    var $limit = 10;
    
    function CommentsList(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
    }
    
    function run($hook, &$hook_data) {
        
        $frontend =& $this->_frontend;
        
        $tpl =& $frontend->tpl;
        $db =& $frontend->db;
        $date_format = (empty($this->date_format) ? $frontend->options['date_format'] : $this->_date_format);
        
        $tpl->setFile('plugin_commentslist', 'plugins/comments_list.xml');
        
        $q = "select
                c.comment_id as id, c.comment_author as author, unix_timestamp(c.comment_date_gmt) as tstamp,
                p.id as post_id, p.post_title, p.post_name, unix_timestamp(p.post_date) as post_tstamp, p.post_category
            from
                " . $frontend->tables['comments'] . " c
            inner join
                " . $frontend->tables['posts'] . " p on c.comment_post_id=p.id
            where
                p.post_status='publish' and p.post_date_gmt <= '" . $frontend->where_date . "'
                and c.comment_approved='1'
            order
                by tstamp desc
            limit 0, " . $this->limit;
        
        if (!$db->query($q))
            return $this->hide();
        
        $comments = array();
        foreach ($db->all() as $k => $v) {
            $v['tstamp'] = (int)$v['tstamp'];
            $v['post_tstamp'] = (int)$v['post_tstamp'];
            $v['permalink'] = $this->_frontend->getPermalink($v['post_id'], $v['post_name'], $v['post_tstamp'], $v['post_category']);
            $v['date'] = strftime($date_format, $v['tstamp']);
            $v['short_date'] = strftime($frontend->options['short_date_format'], $v['tstamp']);
            $comments[] = $v;
        }
        $tpl->parseBlock('PLUGIN_COMMENTSLIST_POST', 'plugin_commentslist_comment', $comments, 'plugin_commentslist');
        $tpl->parse('PLUGIN_COMMENTSLIST', 'plugin_commentslist');
    }
    
}

?>